package com.echo.im.engin.pipeline;

import com.echo.im.common.contant.RedisConstants;
import com.echo.im.common.dto.MessageDTO;
import com.echo.im.engin.packet.in.GroupMessageInPacket;
import com.echo.im.common.vo.GroupMessageVO;
import com.echo.im.domain.group.manager.GroupMemberManager;
import com.echo.im.infrastructure.mq.event.model.store.GroupStoreMessageEvent;
import com.echo.im.infrastructure.session.UserSession;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author: echo
 * @time: 2024-08-23
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class GroupMessageProcessPipeline extends AbstractMessageProcessPipeline<GroupMessageInPacket, GroupMessageVO> {

    private final GroupStoreMessageEvent groupStoreMessageEvent;
    private final GroupMemberManager groupMemberManager;
    private final RedisTemplate<String, Object> redisTemplate;

    @Override
    protected void validateUser(UserSession session, MessageDTO<GroupMessageInPacket> dto) {
        GroupMessageInPacket packet=dto.getPacket();
        // 找到并验证自己是否在群聊
        if (!dto.getIsAnonymous()){
            groupMemberManager.findAndCheckMemberByGroupAndUserId(packet.getGroupId(), session.getUserId());
        }
    }

    @Override
    protected GroupMessageVO createMessageVO(UserSession session, MessageDTO<GroupMessageInPacket> dto) {
        // 发送消息以及入库
        GroupMessageInPacket packet=dto.getPacket();
        GroupMessageVO groupMessageVO = new GroupMessageVO();

        //设置orderId防丢
        String key = RedisConstants.GROUP_MESSAGE_ID + ":" + packet.getGroupId();
        Long orderId =(Long) redisTemplate.opsForValue().increment(key);
        groupMessageVO.setOrderId(orderId);

        groupMessageVO.setContent(packet.getContent());
        groupMessageVO.setGroupId(packet.getGroupId());
        groupMessageVO.setReceipt(packet.getReceipt());
        groupMessageVO.setAtUserIds(packet.getAtUserIds());
        groupMessageVO.setSendId(session.getUserId());
//        groupMessageVO.setSendNickName(member.getShowNickName());
        groupMessageVO.setSendTime(new Date());
        return groupMessageVO;
    }

    @Override
    protected List<Long> getRecvIds(GroupMessageVO messageVO) {
        // 群聊成员列表
        List<Long> userIds = groupMemberManager.findUserIdsByGroupId(messageVO.getGroupId());
        // 不用发给自己
        userIds = userIds.stream().filter(id -> !messageVO.getSendId().equals(id)).collect(Collectors.toList());
        return userIds;
    }

    @Override
    protected void persistMessage(GroupMessageVO messageVO) {
        eventPublisher.publish(groupStoreMessageEvent, messageVO);
    }



}
